<?php

declare(strict_types=1);

namespace App\Statistics\Service;

use App\Common\Service\BaseService;

class RedisManagerService extends BaseService
{
    protected $type = ['string','set','list','zset','hash','other'];

    public function confList(){
        $conf = config('redis');
        $list = [];
        foreach ($conf as $k => $v){
            $list[$k]['dbName'] = $k;
            $list[$k]['dbNum'] = $v['db'];
        }
        return $list;
    }

    public function keys(string $dbName){
        $redis = $this->getRedis($dbName);
        $iterator = null;
        $list = [];
        $i = 0;
        while(false !== ($keys = $redis->scan($iterator))) {
            foreach($keys as $key) {
                $i = ++$i;
                $list[$i]['dbName'] = $dbName;
                $list[$i]['keyName'] = $key;
            }
        }
        return $list;
    }


    public function value(string $dbName, string $keyName){
        // 类型、过期时间
        $redis = $this->getRedis($dbName);
        $type = $redis->type($keyName);
        $ttl = $redis->ttl($keyName);
        switch ($type){
            case 1:
                $value = $redis->get($keyName);
                break;
            case 2:
                $iterator = null;
                $value = $redis->sScan($keyName, $iterator);
                break;
            case 3:
                $value = $redis->lRange($keyName, 0, -1);
                break;
            case 4:
                $iterator = null;
                $value = json_encode($redis->zScan($keyName, $iterator));
                break;
            case 5:
                $value = json_encode($redis->hGetAll($keyName));
                break;
            default:
        }
        return ['ttl' => $ttl, 'type' => $this->type[$type-1],'value' => $value];
    }

    /**
     * redis 实例
     * @param string $dbName
     * @return \Hyperf\Redis\RedisProxy|\Redis|null
     */
    public function getRedis(string $dbName){
        switch ($dbName){
            case 'default':
                $redis = $this->redis;
                break;
            case 'group':
                $redis = $this->groupRedis;
                break;
            case 'user':
                $redis = $this->userRedis;
                break;
            case 'resource':
                $redis = $this->resourceRedis;
                break;
            case 'seckill':
                $redis = $this->seckillRedis;
                break;
            case 'sms':
                $redis = $this->smsRedis;
                break;
            case 'build':
                $redis = $this->buildRedis;
                break;
            default:
        }
        return $redis;
    }
}
